package cn.founder.basic.inInterceptor;

import cn.founder.basic.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component//交给 拦截器管理
public class LoginInterceptor implements HandlerInterceptor{

    //注入redis 操作
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //从请求头中获取token
        String token = request.getHeader("token");
        //请求头重如果有token
        if(!StringUtils.isEmpty(token)){
            //从redis数据库中取出token存储的loginInfo对象
            Object o = redisTemplate.opsForValue().get(token);
            if(o != null){
                redisTemplate.opsForValue().set(
                        token,  //   随机串
                        o,  // 账户的信息
                        30,  //30分钟过期
                        TimeUnit.MINUTES
                );
                //重新设置过期时间后放行
                return true;
            }
        }
        //没有拿到  直接报错
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        //设置好响应的格式
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");

        writer.flush();
        writer.close();
        return false;
    }
}
